﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml.Linq;

namespace ReporterEngine
{
    public partial class sQuery
    {
        // get available properties
        // reference
        //
        // used by

        public DefObject GetDefinition()
        {
            var result = new DefObject();

            foreach(var element in this.Elements)
            {
                var id = this._model.GetID(element);

                foreach(var property in element.Elements())
                {
                    if(property.Attribute(XName.Get("refid")) == null)
                    {
                        if (result.Properties.Where(x => x.PropertyName == property.Name.LocalName).SingleOrDefault() == null)
                        {
                            var newProperty = new DefProperty {PropertyName = property.Name.LocalName};

                            result.Properties.Add(newProperty);
                        }
                    }

                    if (property.Attribute(XName.Get("refid")) != null)
                    {
                        if (result.Referencies.Where(x => x.PropertyName == property.Name.LocalName).SingleOrDefault() == null)
                        {
                            var newReference = new DefReference {PropertyName = property.Name.LocalName};

                            result.Referencies.Add(newReference);
                        }
                    }
                }

                //get all usedby
                if (_model.REFs.ContainsKey(id.ToString()))
                {
                    var refs = this._model.REFs[id.ToString()];

                    foreach (var curRef in refs)
                    {
                        var typeName = _model.GetTypeName(curRef);

                        var newUsedBy = new DefUsedBy() { PropertyName = curRef.Name.LocalName, TypeName = typeName };

                        if (result.UsedBy.ContainsKey(newUsedBy.ToString()))
                        {
                            result.UsedBy.Add(newUsedBy.ToString(), newUsedBy);
                        }
                    }
                }
            }

            return result;
        }
    }
}
